<?php

namespace App\Http\Controllers;

use App\Address;
use Illuminate\Http\Request;
use App\User;

class UserController extends Controller
{
    //
    public function index(User $user)
    {
    	return view("user.index",compact("user"));
    }

    public function address()
    {
    	$user = User::find(\Auth::id());
    	return view("user.address",compact("user"));
    }

    public function addressAdd()
    {
    	return view("user.addAddress");
    }

    public function addressAddCheck(Request $request)
    {
    	$this->validate($request,[
    		'name'=>[
                "unique:users",
                'required',
                'max:20|min:2'
            ],
            'phone'=>[
                "unique:users",
                'required',
                'regex:/^1[1-9]{1}[0-9]{9}$/'
            ],
            'address'=>"required|max:20|min:2",
            'citydesc'=>"required|max:50|min:2",

    	]);
    	$address = request(["name","phone","address","citydesc","city","province","area"]);
    	$address["user_id"] = \Auth::id();
    	\App\Address::create($address);

    	return redirect("/address");
    }

    public function changeAddress(Request $request)
    {
        $user = User::find(\Auth::id());
        $user->address_id = $request->address_id;
        $user->save();
        return [
            "error"=>0,
        ];
    }

    public function delAddress(\App\Address $address)
    {
        $address->delete();
        return[
            "error"=>0
        ];
    }

    public function editAddress(\App\Address $address)
    {
        return view("user.editAddress",compact("address"));
    }

    public function editAddressCheck(Request $request, Address $address)
    {
        $this->validate($request,[
            'name'=>[
                'required',
                'max:20|min:2'
            ],
            'phone'=>[
                'required',
                'regex:/^1[1-9]{1}[0-9]{9}$/'
            ]
        ]);
        $address->name = $request->name;
        $address->phone = $request->phone;
        $address->save();

        return redirect("/address");
    }

}
